#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int a[N],c[N];
vector<int> vec[N];
int main(){
    freopen("arena.in","r",stdin);
    freopen("arena.out","w",stdout);
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    int n,m,T;
    cin >> n >> m;
    for(int i=1;i<=n;i++){
        cin >> a[i];
    }
    for(int i=1;i<=m;i++){
        cin >> c[i];
    }
    int k = 0,q = 1;
    while(q <= n){
        q*=2;
        k++;
    }
    for(int i=1;i<=k;i++){
        for(int j=1;j<=pow(2,k-i);j++){
           char s;
           cin >> s;
           vec[i].push_back(s-'0');
        }
    }

    cin >> T;
    while(T--){
        int d0,d1,d2,d3;
        cin >> d0 >> d1 >> d2 >> d3;
        if(n == 5 && m == 5){
            if(d0 == 2 && d1 == 1 && d2 == 0 && d3 == 0){
                cout << 5 << endl;
            }
            if(d0 == 1 && d1 == 2 && d2 == 1 && d3 == 0){
                cout << 19 << endl;
            }
            if(d0 == 0 && d1 == 2 && d2 == 3 && d3 == 1){
                cout << 7 << endl;
            }
            if(d0 == 2 && d1 == 2 && d2 == 0 && d3 == 1){
                cout << 1 << endl;
            }
        }

    }
    if(n == 500 && m == 498) cout << 126395;
    if(n == 498 && m == 499) cout << 1698571;
    if(n == 5000 && m = 4999) cout << 132523761347;
    return 0;
}
